#include <utillib/script/xmlobject.h>

using namespace utillib::script;

XMLObject::XMLObject() : m_xmlNode( NULL ), m_xmlElement( NULL ), m_xmlAttribute( NULL )
{
}

XMLObject::~XMLObject()
{
}

bool XMLObject::load( char *filename )
{
	m_xmlNode = NULL;
	m_xmlElement = NULL;
	m_xmlAttribute = NULL;
	if ( !m_xmlDocument.LoadFile( filename ) ) return ( false );

	m_xmlNode = m_xmlDocument.FirstChild();
	if ( m_xmlNode ) toElement();

	return ( true );
}

bool XMLObject::getNext( char *name )
{
	if ( !m_xmlNode ) return ( false );
	TiXmlNode *node = NULL;
	if ( name ) node = m_xmlNode->NextSibling( name );
		else node = m_xmlNode->NextSibling();
	if ( !node )  return ( false );
	m_xmlNode = node;

	toElement();

	return ( true );

}

TiXmlNode *XMLObject::getChild()
{
	if ( !m_xmlNode ) return ( false );

	TiXmlNode *parent = m_xmlNode;
	TiXmlNode *node = m_xmlNode->FirstChild();
	if ( !node )  return ( false );

	setNode( node );

	return ( parent );
}

bool XMLObject::setNode( TiXmlNode *node , bool settingElement )
{
	m_xmlNode = node;

	if ( settingElement )  toElement();

	return ( true );
}

bool XMLObject::isExistChild()
{
	if ( !m_xmlNode ) return ( false );
	TiXmlNode *node = m_xmlNode->FirstChild();
	if ( node )  return ( true );
	return ( false );
}

const char *XMLObject::getName()
{
	if ( !m_xmlAttribute ) return ( NULL );
	return ( m_xmlAttribute->Name() );
}

const char *XMLObject::getValue()
{
	if ( !m_xmlAttribute ) return ( NULL );
	return ( m_xmlAttribute->Value() );
}


int XMLObject::getIntValue()
{
	if ( !m_xmlAttribute ) return ( -1 );
	return ( m_xmlAttribute->IntValue() );

}

const char *XMLObject::getTitle()
{
	if ( !m_xmlNode ) return ( NULL );
	return ( m_xmlNode->Value() );
}

bool XMLObject::getNextValue()
{
	if ( m_xmlAttribute ) m_xmlAttribute = m_xmlAttribute->Next();
	else  if ( m_xmlElement ) m_xmlAttribute = m_xmlElement->FirstAttribute();

	return ( m_xmlAttribute != NULL ? true : false );
	
}

bool XMLObject::firstChild( char *name )
{
	TiXmlNode *node = m_xmlDocument.FirstChild( name );
	if ( !node ) return ( false );

	setNode( node );

	return ( true );
}

void XMLObject::toElement()
{
	m_xmlElement = m_xmlNode->ToElement();
	m_xmlAttribute = NULL;
}

TiXmlNode *XMLObject::getNode()
{
	return ( m_xmlNode );
}

const char *XMLObject::getText()
{
	if ( !m_xmlElement ) return ( NULL );
	return ( m_xmlElement->GetText() );
}
